import React, { useEffect, useRef, useState } from 'react';
import useLocale from '@/utils/useLocale';
import { UploadFile } from '@/api/modules';
import { Message, Spin } from '@arco-design/web-react';

import styles from './style/index.module.less';

type PermissionWrapperProps = {
  backup?: React.ReactNode;
  refNumber?: string;
  onFile: (file: { href: string }[]) => void;
  tips?: string;
  maxFileNum?: number;
  fileNum?: number;
};

function AppUpload(props: React.PropsWithChildren<PermissionWrapperProps>) {
  const t = useLocale();

  const fileTypes = [
    'image/pjpeg',
    'image/jpeg',
    'image/png',
    'application/msword',
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    'application/vnd.openxmlformats-officedocument.presentationml.presentation',
    'application/vnd.ms-excel',
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    'application/pdf',
  ];

  const [uploadedFiles, setUploadedFiles] = useState<{ href: string }[]>();
  useEffect(() => {
    if (uploadedFiles && uploadedFiles.length > 0) {
      props.onFile(uploadedFiles);
    }
  }, [uploadedFiles]);

  const fileInputRef = useRef<HTMLInputElement | null>(null);
  const handleFileSelect = () => {
    if (fileInputRef.current) {
      fileInputRef.current.value = '';
      fileInputRef.current.click();
    }
  };

  const handleFileUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = e.target.files;
    console.log(files);
    if (files) {
      // 检测文件
      const maxSize = 200 * 1024 * 1024;
      const maxNum = 5;
      const filesList = Array.from(files);

      //检测外部条件
      const { tips = t['upload.tips'], maxFileNum = 100, fileNum } = props;
      if (maxFileNum) {
        console.log(tips, maxFileNum, fileNum);
        if (fileNum + filesList.length > maxFileNum) {
          Message.warning(tips);
          return;
        }
      }
      if (filesList.length > maxNum) {
        Message.warning(t['upload.maxNum']);
        return;
      }
      const isSize = filesList.some((a) => a.size > maxSize);
      console.log(isSize);
      // const sum = (prev: number, cur: File) => prev + cur.size;
      // const size = filesList.reduce(sum, 0);
      if (isSize) {
        Message.warning(t['upload.maxSize']);
        return;
      }

      let isTypeError = false;
      filesList.forEach((file: File) => {
        if (!fileTypes.includes(file.type)) {
          isTypeError = true;
          Message.warning(t['upload.type']);
          return false;
        }
      });
      if (isTypeError) {
        return;
      }
      setLoading(true);
      //上传
      try {
        const uploadPromises = filesList.map(async (file) => {
          const excelFormData = new FormData();
          excelFormData.append('file', file);
          if (!!props.refNumber) {
            excelFormData.append('refNumber', props.refNumber);
          }

          const { data } = await UploadFile(excelFormData);
          return { href: data };
        });
        const uploadedFile = await Promise.all(uploadPromises);
        setUploadedFiles(() => uploadedFile);
      } finally {
        setLoading(false);
      }
    }
  };

  function convertReactElement(node: React.ReactNode): React.ReactElement {
    if (!React.isValidElement(node)) {
      return <>{node}</>;
    }
    return node;
  }

  const [loading, setLoading] = useState<boolean>(false);
  return (
    <>
      {loading && (
        <div className={styles['loading']}>
          <Spin size={40} />
        </div>
      )}

      <div onClick={handleFileSelect}>
        {convertReactElement(props.children)}
        <input
          size={5}
          type="file"
          multiple
          ref={fileInputRef}
          style={{ display: 'none' }}
          onChange={handleFileUpload}
          accept=".jpeg,.png,.doc,.docx,.ppt,.pptx,.xls,.xlsx,.pdf"
        />
      </div>
    </>
  );
}

export default AppUpload;
